package com.tubeonfire.util;

import java.io.IOException;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.blobstore.BlobKeyProcess;
import com.tubeonfire.entity.Playlist;

public class PlaylistValidate {

	private static final Logger log = Logger.getLogger(PlaylistValidate.class
			.getName());

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean checkForm(HttpServletRequest req,
			HttpServletResponse resp, HttpSession session, String action,
			Playlist pl) {
		try {
			TreeMap check = new TreeMap();
			String title = (String) req.getParameter("title");
			String description = (String) req.getParameter("description");
			String imgKey = BlobKeyProcess.getBlobKey(req, "image");
			if (title == null || title.isEmpty()) {
				check.put("title", "Title's required !");
			} else {
				pl.setTitle(title);
				pl.setAlias(StringHelper.getAliasByLanguage(title));
			}
			if (description == null || description.isEmpty()) {
				check.put("description", "Description's required !");
			} else {
				pl.setDescription(description);
			}
			if (action.equals("add")) {
				if (imgKey == null || imgKey.isEmpty()) {
					check.put("image", "Cover Image's required !");
				} else {
					pl.setImageKey(imgKey);
				}
			} else if (action.equals("edit")) {
				if (imgKey != null && !imgKey.isEmpty()) {
					pl.setImageKey(imgKey);
				}
			}

			if (check.size() > 0) {
				session.setAttribute("return", true);
				session.setAttribute("check", check);
				session.setAttribute("error",
						"Please fix errors below to finish action !");
				session.setAttribute("pl", pl);
				resp.sendRedirect("/admin/playlist/add");
				return false;
			} else {				
				return true;
			}
		} catch (IOException e) {
			log.warning(e.toString());
			e.printStackTrace();
			return false;
		}
	}
}
